from app.common.mysql.operate import db
def insert_user(param):
    columns = ', '.join(param.keys())  # 获取字典的键作为列名
    placeholders = ', '.join(['%s'] * len(param))  # 生成占位符
    sql = f"INSERT INTO user ({columns}) VALUES ({placeholders})"
    
    # 参数元组
    args = tuple(param.values())  # 获取字典的值作为参数
    return db.execute_db(sql, args)


def update_user(param):
    sql = """
    UPDATE `user` SET username = %s, password = %s, question1 = %s, question2 = %s, answer1 = %s, answer2 = %s, mobile = %s WHERE id = %s
    """
    args = (param['username'], param['password'], param['question1'], param['question2'], param['answer1'], param['answer2'], param['answer2'], param['id'])
    return db.execute_db(sql, args)

def select_user(param):
    # 动态构建 WHERE 子句
    where_clauses = []
    args = []

    # 动态生成查询条件
    for key, value in param.items():
        if isinstance(value, list):  # 如果是列表，表示有多个条件
            for condition in value:
                operator, val = condition
                where_clauses.append(f"{key} {operator} %s")
                args.append(val)
        elif isinstance(value, tuple):  # 如果是元组，表示单个条件
            operator, val = value
            where_clauses.append(f"{key} {operator} %s")
            args.append(val)
        else:  # 默认是等于操作
            where_clauses.append(f"{key} = %s")
            args.append(value)

    # 将 WHERE 子句连接起来
    where_sql = " AND ".join(where_clauses) if where_clauses else "1"  # 默认查询所有记录

    # 完整的 SQL 查询
    sql = f"SELECT * FROM user WHERE {where_sql}"
    return db.select_db(sql, args)
